package org.yan.kangaroo.storage.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yan.kangaroo.common.frs.vo.request.UploadFileBase64Request;
import org.yan.kangaroo.common.response.Result;
import org.yan.kangaroo.pojo.storage.entity.FileResource;
import org.yan.kangaroo.storage.service.FileResourceService;
import org.yan.kangaroo.storage.service.FileStorageFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangx
 * @date 11/14/2019 10:20
 */
@RestController
@RequestMapping("/internal/api/v1/files")
@Slf4j
@AllArgsConstructor
@Api(tags = "文件管理API")
public class FileResourceController {
    private final FileStorageFactory fileStorageFactory;

    private final FileResourceService fileResourceService;

    @PostMapping(value = "/upload/base64")
    @ApiOperation(value = "Base64编码上传文件")
    public Result<FileResource> uploadBase64(@RequestBody @Validated UploadFileBase64Request request) {
        log.info("[uploadBase64] begin request params:{}", request);
        FileResource resource = fileStorageFactory.uploadObject(request);
        log.info("[uploadBase64] end result:{}", resource);
        return Result.ok(resource);
    }

    @PostMapping(value = "/upload")
    @ApiOperation(value = "上传文件")
    public Result<FileResource> uploadFile(@RequestParam("file") MultipartFile file,
                                           @RequestParam(value = "storageType", defaultValue = "aliyun") String storageType) {
        log.info("[uploadFile] begin request params:{}", file.getOriginalFilename());
        FileResource resource = fileStorageFactory.uploadFile(file, storageType);
        log.info("[uploadBase64] end result:{}", resource);
        return Result.ok(resource);
    }

    @GetMapping(value = "/preview/{fileId}")
    public void previewFile(@PathVariable("fileId") Long fileId, HttpServletResponse response) throws IOException {
        log.info("[previewFile] begin request fileId:{}", fileId);
        FileResource fileResource = fileResourceService.findByFileId(fileId);
        InputStream inputStream = fileStorageFactory.getObject(fileResource.getKeyword(), fileResource.getStorageType());
        response.setContentType(fileResource.getContentType() + ";charset=utf-8");
        IOUtils.copy(inputStream, response.getOutputStream());
    }

    @GetMapping(value = "/{fileId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<FileResource> getInfo(@PathVariable("fileId") Long fileId) {
        return Result.ok(fileResourceService.findByFileId(fileId));
    }


}
